define(["underscoreBase", "marionette", "vent" ], function(_, Marionette, vent) {

	var LoginView = Marionette.CompositeView.extend({

			template: "#tpl-login-panel",
			
			ui : {
				usernameField : '#username',
				passwordField : '#password',
				loginBtn : '#loginBtn'
			},

			events : {
				"keyup @ui.usernameField, @ui.passwordField" : "checkForEnter",
				"click @ui.loginBtn" : "tryToLogin"
			},
			
			checkForEnter : function(e) {

				if(e.keyCode == 13){
					this.tryToLogin();
				}
			},
			
			isFormValid : function(){
				return this.ui.usernameField.val() != '' && this.ui.usernameField.val().length > 0
				&& this.ui.passwordField.val() != '' && this.ui.passwordField.val().length > 0;
			},
			
			tryToLogin :  function(){
				
				if(this.isFormValid()){
					
					this.doLogin();
					
				}else{
					
					vent.trigger("showError", messages.error.label(), messages.error.login.invalid.message());
				}
			},
			
			doLogin : function(){
				
				var authToken = this.ui.usernameField.val()+":"+this.ui.passwordField.val();
				var that = this;
				
				$.ajax({
					type: 'POST',
				    contentType: 'application/json',
				    url: "/KeyChain/login/doLogin",
				    
				    username: this.ui.usernameField.val(),
				    password: this.ui.passwordField.val(),
				    
				    dataType: "json",
				    data: JSON.stringify({username:this.ui.usernameField.val(), password:this.ui.passwordField.val()}),
				        
				    beforeSend: function(xhr) { 
				    	xhr.setRequestHeader("Authorization", "Basic " + btoa(authToken)); 		        	
				    },
				        
				    success: function(data, textStatus, jqXHR){
				    	if(data.isLoggedIn){
				    		vent.trigger("userIsLoggedIn", that.ui.usernameField.val(), that.ui.passwordField.val());
				        }else{
				        	vent.trigger("showError",messages.error.unknown.label() ,messages.error.unknown.message());
				        }
				    },
				    
				    error: function(jqXHR, textStatus, errorThrown){
				        	
				    	if(jqXHR.status == 401){
				        		
				    		vent.trigger("showError", messages.error.login.invalid.label(), messages.error.login.invalid.message());
				        		
				        }else{
				        	
				        	vent.trigger("showError", messages.error.unknown.label(), errorThrown);
				        }

				   }
				});
			}
		});
		
	return LoginView;
});